package cn.school.web;

import cn.school.entity.Grade;
import cn.school.entity.Page;
import cn.school.entity.Student;
import cn.school.service.GradeService;
import cn.school.service.StudentService;
import cn.school.service.SubjectService;
import cn.school.util.LogUtil;
import cn.school.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
@WebServlet("*.cmd")// 斜杠不能要
public class CommonServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("text/html;charset=utf-8");
//        PrintWriter out = resp.getWriter();
//        out.print("<html>");
//        out.print("<body>");
//        out.print("<h1>");
//        out.print("上下文根：" + req.getContextPath());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("服务器信息：" +req.getScheme()+"="+ req.getServerName()+":"+req.getServerPort());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("URI：" + req.getRequestURI());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("URL：" + req.getRequestURL());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("查询字符串：" + req.getQueryString());
//        out.print("</h1>");
//        out.print("<h1 style='font-size:90px;color:red;'>");
//        out.print("服务器端程序地址：" + req.getServletPath());
//
//
//        out.print("</h1>");
        String path = req.getServletPath();
        path = path.substring(1, path.length() - 4);//action
        //out.print("<div>");
        try {
            Method method = this.getClass().getDeclaredMethod(path, HttpServletResponse.class, HttpServletRequest.class);
            Object r = method.invoke(this, resp, req);
            if (r != null && r instanceof String) {
                req.getRequestDispatcher((String) r).forward(req, resp);
            }
        } catch (Exception e) {
            //resp.getWriter().print("此操作有错误！"+e);
            e.printStackTrace();
            throw new RuntimeException(e);
        }

//        if(path.equals("login"))
//        {
        //  login(resp, req);
//            //...
//        }
//        else if(path.equals("update"))
//            out.print("这是更新");
//        else if(path.equals("addsubject"))
//            out.print("这是增加课程");
//        else
//            out.print("未知操作");
//        out.print("</div>");
//        out.print("</body>");
//        out.print("</html>");
    }

    public String showstu(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        long stuno=StringUtil.toLong(req.getParameter("stuno"));
        req.setAttribute("stu",StudentService.INST.get(stuno));

        return "/WEB-INF/jsp/studentshow.jsp";
    }

    //视图地址
    public String login(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        String u = req.getParameter("uname");
        String p = req.getParameter("pass");
        if ("admin".equals(u) && "123".equals(p))
            resp.getWriter().print("登录成功");
        else
            resp.getWriter().print("登录成功");

        return null;
    }

    public String stuUpdate(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        long stuno = 12L;
        req.setAttribute("student", stuno);
        return "/WEB-INF/jsp/studentupdate.jsp";
    }

    public void checkSubjectName(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        String subject = req.getParameter("subjecname");
        LogUtil.Log.info("subject=" + subject);
//        try {
//            Thread.sleep(3599);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        if(Math.random()>0.1)
//            throw  new RuntimeException("超时");

        boolean b = SubjectService.INST.checkSubName(subject);
        resp.getWriter().print(b);

    }

    public void grades(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        List<Grade> list = GradeService.INST.findALL();
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < list.size(); i++) {
            sb.append("{");
            sb.append("\"id\":");
            sb.append(list.get(i).getId() + ",");
            sb.append("\"gname\":");
            sb.append("\"" + list.get(i).getGname() + "\"");
            sb.append("}");
            if (i < list.size() - 1)
                sb.append(",");
        }
        sb.append("]");
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(sb);
    }

    public void studentSearch(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        int pageNo = StringUtil.toIntGt0(req.getParameter("pageNo"), 1);
        int pageSize = 10;
        String sname = StringUtil.trimNull(req.getParameter("sname"));
        String qq = StringUtil.trimNull(req.getParameter("qq"));
        String telephone = StringUtil.trimNull(req.getParameter("telephone"));
        Date startDate = StringUtil.toDate(req.getParameter("startDate"));
        Date end= StringUtil.toDate(req.getParameter("endDate"));
        Page<Student> page = StudentService.INST.search(pageNo, pageSize, sname, qq, telephone,startDate,end);

        String s = JSON.toJSONStringWithDateFormat(page,"yyyy-MM-dd", SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(s);

//        req.setAttribute("stus",page);
//        req.setAttribute("sname",sname);
//        req.setAttribute("qq",qq);
//        req.setAttribute("startDate",startDate);
//        req.setAttribute("endDate",end);
//        req.setAttribute("telephone",telephone);

    }
}
